from logging.handlers import RotatingFileHandler
import logging
from flask import Flask
from flask import g
from flask import render_template
from flask_wtf.csrf import CSRFProtect
from flask_sqlalchemy import SQLAlchemy
import redis
from flask_session import Session
from redis import StrictRedis

from config import DevelopmentConfig,ProductionConfig
from config import config
from info.utils.common import do_index_class, user_login_data

db = SQLAlchemy()
redis_store=None

def create_app(config_name='development'):
    setup_log(config_name)
    # 实例flask对象
    app = Flask(__name__)



    # 实例所有配置的对象
    app.config.from_object(config[config_name])
    # global db
    # db=
    db.init_app(app)
    global redis_store
    redis_store = StrictRedis(host=config[config_name].REDIS_HOST, port=config[config_name].REDIS_PORT)
    # 4实例csrf
    CSRFProtect(app)
    # 生成csrf_token

    Session(app)
    from info.modules.index import index_blu
    app.register_blueprint(index_blu)
    from info.modules.passport import passport_blu
    app.register_blueprint(passport_blu)
    from info.modules.news import news_blu
    app.register_blueprint(news_blu)
    from info.modules.profile import profile_blu
    app.register_blueprint(profile_blu)

    @app.after_request
    def after_request(resp):
        # 调用函数生成 csrf_token
        from flask_wtf.csrf import generate_csrf
        token = generate_csrf()
        # 通过 cookie 将值传给前端
        resp.set_cookie("csrf_token", token)
        return resp

    # 添加过滤器

    app.add_template_filter(do_index_class, "index_class")
    # 添加404网页
    @app.errorhandler(404)
    @user_login_data
    def page_not_found(_):
        user = g.user
        data = {"user_info": user.to_dict() if user else None}
        return render_template('news/404.html', data=data)
        return app

    return app


def setup_log(config_name):


    logging.basicConfig(level=config[config_name].LOG_LEVEL)

    file_log_handler = RotatingFileHandler("logs/log", maxBytes=1024 * 1024 * 100, backupCount=10)

    formatter = logging.Formatter('%(levelname)s %(filename)s:%(lineno)d %(message)s')

    file_log_handler.setFormatter(formatter)

    logging.getLogger().addHandler(file_log_handler)
